import 'package:dio/dio.dart';
import 'package:flutter/widgets.dart';
import 'dart:convert';
import 'dart:io';

import 'package:shop/http/response_result.dart';

class HttpUtils{
  static HttpUtils instance;
  Dio dio;
  BaseOptions options;

  static HttpUtils getInstance(){
    if(instance == null){
      instance = new HttpUtils();
    }

    return instance;
  }

  HttpUtils(){
    var userAgent;
    if (Platform.isAndroid){
      userAgent = "Android";
    }else if(Platform.isIOS){
      userAgent = "IOS";
    }else{
      userAgent = "Unknown";
    }
    options = new BaseOptions(
      baseUrl: "http://icms.inchwell.com.cn/api",
      //连接服务器的超时时间
      connectTimeout: 5000,
      //响应流上前后两次接收数据的间隔，单位毫秒，如果两次间隔超过
      //会抛出异常[DioErrorType.RECEIVE_TIMEOUT]
      receiveTimeout: 3000,
      headers:{HttpHeaders.acceptHeader:"accept: application/json; user-agent:" + userAgent  + "\""}
    );
    dio = new Dio(options);
  }

  get(url, Function callback, {options, cancelToken}) async{
    print('get请求url:$url');
    Response response;
    try{
      response = await dio.get(
        url,
        cancelToken: cancelToken,
      );
      print('get请求成功！response.data:${response.data}');
    } on DioError catch(e){
      if(CancelToken.isCancel(e)){
        print('get请求取消' + e.message);
      }
      print('get请求错误：$e');
    }

    return response.data;
  }

  post(url, Function callback, {data, options, cancelToken}) async{
    print('post请求url:$url,内容body:$data');
    Response response;
    try{
      response = await dio.post(
        url,
        data: data,
        cancelToken: cancelToken,
      );

      if(response.statusCode == 200){
        print('post请求成功！response.data:${response.data}');

        Map<String, dynamic> map = json.decode(response.data);

        var result = new Result.fromJson(map);

        if(result.code == '0'){
          callback(json.encode(result.data));
        }else{
          _handError(result.code, result.msg, callback);
        }
      }else{
        print('post请求数据返回失败，response.statusCode:${response.statusCode}');
      }
    } on DioError catch(e){
      if(CancelToken.isCancel(e)){
        print('post请求取消' + e.message);
      }
      print('post请求错误：$e');
    }
  }

  Future<Response> postFuture(url, {data, options, cancelToken}) async{
    print('post请求url:$url,内容body:$data');
    try{
      return await dio.post(
        url,
        data: data,
        cancelToken: cancelToken,
      );
    } on DioError catch(e){
      if(CancelToken.isCancel(e)){
        print('post请求取消' + e.message);
      }
      print('post请求错误：$e');
    }
  }

  //异常处理
  void _handError(String code, String msg, Function errorCallback){
    switch(code){
      case "":
        break;
    }
  }
}